package com.qiaofang.collectmanage.service.common.utils.phone;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

public class AESCipher {

    /** 算法/模式/填充
     * AES/ECB/PKCS5Padding **/
    private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";
    /**密钥长度**/
//    //256 bits or 128 bits,192bits
//    private static final int KEY_LENGTH = 128;
    /**
     *
     * TODO(加密)
     * @Title: encrypt
     * @return String
     * @Exception
     */
    public static String encrypt(String key, String src) throws Exception {
        byte[] rawKey = getRawKey(key.getBytes());
        byte[] result = encrypt(rawKey, src.getBytes());
        return byte2hex(result);
    }
    /**
     *
     * TODO(解密)
     * @Title: decrypt
     * @return String
     * @Exception
     */
    public static String decrypt(String key, String encrypted) throws Exception {
        byte[] rawKey = getRawKey(key.getBytes());
        byte[] enc = hex2byte(encrypted);
        byte[] result = decrypt(rawKey, enc);
        return new String(result);
    }

    /**
     *
     * TODO(获取秘匙)
     * @Title: getRawKey
     * @return byte[]
     * @Exception
     */
    private static byte[] getRawKey(byte[] seed) throws Exception {
//        KeyGenerator kgen = KeyGenerator.getInstance("AES");
//        // SHA1PRNG ǿ
//        SecureRandom sr = null;
////        if (android.os.Build.VERSION.SDK_INT >=  17) {
////            sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
////          } else {
////            sr = SecureRandom.getInstance("SHA1PRNG");
////          }
////        sr.setSeed(seed);
//        sr = new SecureRandom(seed);
//        kgen.init(KeyLength, sr); //256 bits or 128 bits,192bits
//        SecretKey skey = kgen.generateKey();
//        byte[] raw = skey.getEncoded();
//        return raw;
        KeyGenerator kgen = KeyGenerator.getInstance("AES");

        kgen.init(128, new SecureRandom(seed));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        return enCodeFormat;
    }

    /**
     *
     * TODO(根据密匙加密成Byte数组)
     * @Title: encrypt
     * @return byte[]
     * @Exception
     */
    private static byte[] encrypt(byte[] key, byte[] src) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(src);
        return encrypted;
    }
    /**
     *
     * TODO(根据密匙解密成Byte数组)
     * @Title: decrypt
     * @return byte[]
     * @Exception
     */
    private static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    /** 字节数组转成16进制字符串 **/
    public static String byte2hex(byte[] b) { // 一个字节的数，
        StringBuffer sb = new StringBuffer(b.length * 2);
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            // 整数转成十六进制表示
            tmp = (Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString(); // 转成字符串

    }

    /** 将hex字符串转换成字节数组 **/
    private static byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            result[i] = ((byte)(Integer.parseInt(inputString.substring(i * 2, i * 2 + 1), 16) * 16 +
                    Integer.parseInt(inputString.substring(i * 2 + 1, i * 2 + 2), 16)));
//            String tmp = inputString.substring(2 * i, 2 * i + 2);
//            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }

    public static byte[] parseHexStr2Byte(String paramString)
    {
        if (paramString.length() < 1)
        {
//        LOGGER.s(new RuntimeException("parseHexStr2Byte phonenumber length < 1"));
            return null;
        }
        byte[] arrayOfByte = new byte[paramString.length() / 2];
        int i = 0;
        while (i < paramString.length() / 2)
        {
            arrayOfByte[i] = ((byte)(Integer.parseInt(paramString.substring(i * 2, i * 2 + 1), 16) * 16 + Integer.parseInt(paramString.substring(i * 2 + 1, i * 2 + 2), 16)));
            i += 1;
        }
        return arrayOfByte;
    }

    public static String evalPhone(String phoneNum){
        String phone = "";
        String key = "crazycrazycrazy1";  //秘钥
        try {
            byte[] bb = parseHexStr2Byte(phoneNum.toLowerCase());
            byte[] ss = AESCipher.decrypt(key.getBytes(), bb);
            return new String(ss);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return phone;
    }
    public static void main(String[] args) {
        System.out.println(evalPhone("2221961F1A8C2678496F03B4B1F0A442F50"));
//        String src = "13818329810"; //需加密字段
//        String key = "crazycrazycrazy1";  //秘钥
//        String dest = null;  //加密字符
//        try {
//            byte[] bb = parseHexStr2Byte("2C7123EB7B638016FEC0949D2950D265".toLowerCase());
//            dest = AESCipher.encrypt(key, src);
//            byte[] ss = AESCipher.decrypt(key.getBytes(), bb);
//            System.out.println(new String(ss));
////            System.out.println(dest);
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }

    public static void printByte(byte[] arr) {
        for(int j = 0;j<arr.length;j++) {
            System.out.print(arr[j] + ",");
        }
        System.out.println();
    }
}
